package com.iscas.dataaggregation.utils;

import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;

import java.util.ArrayList;
import java.util.List;

@Component
public class MetricsUtils {

    private static final Logger logger = Logger.getLogger(MetricsUtils.class);

    /**
     * 获取指定服务的指标信息
     *
     * @param namespace  命名空间
     * @param serviceName 服务名称
     * @param startTime   起始时间
     * @param endTime     结束时间
     * @return 服务的所有指标信息列表
     */
    public JsonNode getMetricsForService(String namespace, String serviceName, long startTime, long endTime) {
        // 构造 URL
        String url = "http://60.245.215.207:30080/api/project/pqnv7ole/app/" +
                namespace + ":Deployment:" + serviceName +
                "?from=" + startTime + "&to=" + endTime;

        logger.info("Fetching metrics for service: " + serviceName + " in namespace: " + namespace);
        logger.info("Constructed URL: " + url);

        try {
            // 使用 RestTemplate 发送 GET 请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            // 获取响应 Body
            String body = response.getBody();
            logger.debug("Response body received: " + body);

            // 解析 JSON 数据
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(body);

            // 查找 data.reports 节点
            JsonNode reportsNode = rootNode.path("data").path("reports");

            if (reportsNode.isMissingNode() || !reportsNode.isArray()) {
                logger.warn("No metrics found for service: " + serviceName + " in namespace: " + namespace);
                return null; // 返回 null 表示未找到任何指标信息
            }

            logger.info("Metrics successfully fetched for service: " + serviceName);
            return reportsNode; // 直接返回 reports 节点
        } catch (Exception e) {
            logger.error("Error occurred while fetching metrics for service: " + serviceName, e);
            return null;
        }
    }
}
